import Request from "./request";
import type { RequestConfig } from "./types";
import { getLocal, $notify, removeLocal, setLocal } from "UTILS";
interface BiRequestConfig<T> extends RequestConfig {
  data?: T;
}
interface BiResponse<T> {
  code: number;
  msg: string;
  data: T;
}

const _request = new Request({
  timeout: 1000 * 60,
  headers: { "Content-Type": "application/json" },
  interceptors: {
    // 请求拦截器
    requestInterceptors: (config: any) => {
      if (getLocal("TOKEN")) {
        let _token = getLocal("TOKEN");
        config.headers.Authorization = `Bearer ${_token}`;
      }
      return config;
    },
    // 响应拦截器
    responseInterceptors: (result: any) => {
      if (result.status === 200) {
        // 文件请求
        if (
          result.headers["content-disposition"] &&
          result.headers["content-disposition"].indexOf("attachment") !== -1
        ) {
          return result;
        }
        if (result.data.code === 200) {
          return result.data && result.data.data != null ? result.data.data : result.data;
        } else if (result.data.code === 403 || result.data.code === 401) {
          $notify(result.data.msg ? result.data.msg : "数据加载异常", "error");
        } else {
          if (result.data.type == "application/pdf") {
            return result.data;
          } else {
            $notify(result.data.msg ? result.data.msg : "数据异常，请联系管理员", "error");
          }
        }
      }
    },
    responseInterceptorsCatch: (error: any) => {
      const response = error.response;
      $notify(response?.data?.message);
      // 根据返回的http状态码做不同的处理
      switch (response?.status) {
        case 400:
          //  页面找不到
          $notify("数据加载异常", "error");
          break;
        case 401:
          $notify("数据加载异常");
          break;
        case 403:
          $notify("403 数据加载异常", "error");
          break;
        case 404:
          $notify("404 数据加载异常", "error");
          break;
        case 500:
          // 服务端错误
          $notify("500 数据加载异常", "error");
          break;
        case 503:
          // 服务端错误
          $notify("503 数据加载异常", "error");
          break;
        case 504:
          // 服务端错误
          $notify("504 数据加载异常", "error");
          break;
        default:
          // 接口异常
          break;
      }
    },
  },
});

/**
 * @description: 函数的描述
 * @generic D 请求参数
 * @generic T 响应结构
 * @param {BiRequestConfig} config 不管是GET还是POST请求都使用data
 * @returns {Promise}
 */
const request = <D = any, T = any>(config: BiRequestConfig<D>) => {
  return _request.request<BiResponse<T>>(config);
};
// 取消请求
export const cancelRequest = (url: string | string[]) => {
  return _request.cancelRequest(url);
};
// 取消全部请求
export const cancelAllRequest = () => {
  return _request.cancelAllRequest();
};

export default request;
